﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.Serialization;

namespace PlayBox.DataClasses
{
    /// <summary>
    /// Benutzerdaten wie Benutzername und Passworthash
    /// </summary>
    [Serializable]
    public class UserData
    {
        /// <summary>
        /// Benutzername
        /// </summary>
        public String Username { get; set; }

        /// <summary>
        /// Hash des Passworts
        /// </summary>
        public String Hash { get; set; }

        /// <summary>
        /// Salt, der zum Hashen verwendet wird
        /// </summary>
        public String Salt { get; set; }

        /// <summary>
        /// Generiert den Hash für das angegebene Passwort
        /// </summary>
        /// <param name="password"></param>
        public void SetPassword (String password)
        {
            if (Salt == null || Salt.Length == 0)
                GenerateSalt();

            // Salt davorhängen
            password = Salt + password;

            // Verschlüsseln
            Hash = CalculateSHA1(password, Encoding.Default);
        }

        /// <summary>
        /// Generiert einen Salt
        /// </summary>
        private void GenerateSalt ()
        {
            // Anhand GUID Salt erstellen
            String guid = Guid.NewGuid().ToString();
            guid = guid.Replace("-", "");

            this.Salt = guid;
        }

        /// <summary>
        /// SHA1 Hash berechnen
        /// </summary>
        /// <param name="text">Inhalt zu hashen</param>
        /// <param name="enc">Encoding</param>
        /// <returns></returns>
        private string CalculateSHA1(string text, Encoding enc)
        {
            byte[] buffer = enc.GetBytes(text);
            SHA1CryptoServiceProvider cryptoTransformSHA1 = 
                new SHA1CryptoServiceProvider();
            string hash = BitConverter.ToString(
                cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");

            return hash;
        }


        public string GetDirectoryPath(String path)
        {
            return GetDirectoryPath(Username, path);
        }



        public static string GetDirectoryPath (String username, String path)
        {
            return "HDD\\Users\\" + username + "\\" + path;
        }

    }
}
